#include "redstone_line.h"
#include "segment_LED.h"


uint16_t myRS_get_mv(struct redstone_stu *rs){
    uint16_t rs_mv = adc_redstone*real_Vref*0.0014874014874;

    return rs_mv;
}

void myRSL_show_strength(struct redstone_line_stu *rsl){
    RS_strength_t rsl_strength = ReAL_get_strength_min(&rsl->redstone);

    if(rsl_strength < RS_STRENGTH_1){
        SEG_LED_show_num(&mySegLED, SEG_LED_NUM_0);
        Timer14_PWM_Handle.Instance->CCR1 = 100;
    }else if(rsl_strength > RS_STRENGTH_14){
        SEG_LED_show_num(&mySegLED, SEG_LED_NUM_F);
        Timer14_PWM_Handle.Instance->CCR1 = 0;
    }else {
        SEG_LED_show_num(&mySegLED, SEG_LED_NUM_1 + (rsl_strength - RS_STRENGTH_1));
        Timer14_PWM_Handle.Instance->CCR1 = 99 - (rsl_strength - RS_STRENGTH_1)*99/(RS_STRENGTH_15 - RS_STRENGTH_1);
    }
}

void myRSL_led_init(struct redstone_line_stu *rsl){
    TIM_OC_InitTypeDef Timer14_OC_PWM_Config;    /* 定时器PWM输出配置 */

    Timer14_PWM_Handle.Instance = TIM14;
    /* 定时器x */
    Timer14_PWM_Handle.Init.Period = 100 - 1;                                  /* 自动重装载值 */
    Timer14_PWM_Handle.Init.Prescaler = 240 - 1;                                  /* 定时器分频 */
    Timer14_PWM_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;                   /* 向上计数模式 */
    Timer14_PWM_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;             /* 时钟分频因子 */
    Timer14_PWM_Handle.Init.RepetitionCounter = 0;                              /* 不重复计数*/
//    /* 自动重装载寄存器没有缓冲 */
//    Advanced_Timer1_PWM_Handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; 
    HAL_TIM_PWM_Init(&Timer14_PWM_Handle);                                      /* 初始化PWM */

    Timer14_OC_PWM_Config.OCMode = TIM_OCMODE_PWM1;                             /* 模式选择PWM1 */
    Timer14_OC_PWM_Config.Pulse = 100;
    Timer14_OC_PWM_Config.OCPolarity = TIM_OCPOLARITY_HIGH;                     /* 输出比较极性为高 */
    Timer14_OC_PWM_Config.OCFastMode = TIM_OCFAST_DISABLE;
    Timer14_OC_PWM_Config.OCIdleState = TIM_OCIDLESTATE_SET;
    Timer14_OC_PWM_Config.OCNIdleState = TIM_OCNIDLESTATE_RESET;                /*空闲状态OC1N输出低电平 */
    Timer14_OC_PWM_Config.OCIdleState  = TIM_OCIDLESTATE_RESET; 				/*空闲状态OC1输出低电平*/

    /* 配置 TIM14 通道 1 */
    HAL_TIM_PWM_ConfigChannel(&Timer14_PWM_Handle, &Timer14_OC_PWM_Config, TIM_CHANNEL_1);
    /* 使能定时器x和定时器x更新中断 */
    HAL_TIM_PWM_Start(&Timer14_PWM_Handle, TIM_CHANNEL_1);
}
